package com.personal.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBMysql {
    private int num=1;

    public List getTablesInfo(String tableNames) {
        List resultList = new ArrayList();
        String[] tableNameArr = tableNames.split(",");
        for(String tableName:tableNameArr) {
            List tmpResultList = this.getTableInfo(tableName);
            resultList.add(tmpResultList);
        }

        return resultList;
    }

    public List getTableInfo(String tableName) {
        List resultList = new ArrayList();
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://122.96.150.101:8080/jhd_db?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String user = "root";
        String password = "DongRuan@111";

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < tableName.length(); i++) {
            char c = tableName.charAt(i);
            if (c>=0x4e00 && c<=0x9fbb) {
                break;
            }else {
                sb.append(c);
            }
        }
        String realTableName = sb.toString();
        String sql = "show full columns from "+realTableName;
        try {
            // 加载驱动程序
            Class.forName(driver);

            // 连续数据库
            Connection conn = DriverManager.getConnection(url, user, password);
            if (!conn.isClosed())
                System.out.println("Succeededconnecting to the Database!"+(this.num++));

            // statement用来执行SQL语句
            Statement statement = conn.createStatement();

            // 要执行的SQL语句id和content是表review中的项。
            ResultSet rs = statement.executeQuery(sql);

            // 输出id值和content值
            resultList.add(tableName);
            while (rs.next()) {
                String fieldName = rs.getString("Field");
                String fieldType = rs.getString("Type");
                String fieldNull = rs.getString("Null");
                String fieldDefault = rs.getString("Default");
                String fieldComment = rs.getString("Comment");
                //System.out.println( fieldName+""+fieldType+""+fieldNull+fieldDefault+""+fieldComment);
                Map rowMap = new HashMap();
                rowMap.put("fieldName",fieldName);
                rowMap.put("fieldType",fieldType);
                rowMap.put("fieldNull",fieldNull);
                rowMap.put("fieldDefault",fieldDefault);
                rowMap.put("fieldComment",fieldComment);
                resultList.add(rowMap);
            }


            rs.close();
            conn.close();

            return resultList;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("错误："+tableName+":realTableName:"+realTableName);
            return null;
        }
    }
}
